// pages/plugins//chose-address/index.js
import pinyin from "wl-pinyin";
const app = getApp();
const { AskPage } = app._require("common/index");
const formMixin = app._require("mixins/form.mixin.js").default;
import {locationMixin} from "../../../mixins/location"
const QQMapWX = require('../../../libs/qqmap-wx-jssdk.min.js');
AskPage({

  /**
   * 页面的初始数据
   */
  name: "address",
  mixins: [locationMixin],
  data: {
    chose_items:[],
    AlphabetList : ["A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "W", "X", "Y", "Z"]
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
      this.getGovernmentByCode();
      
  },
  clickAddress(){
    console.log("重新定位");
    // console.log(this.data.latitude);
    // locationMixin.onLoad();
    this.getLocation(
      this.data.latitude,
      this.data.latitude,
      true
    );



  },
  choseItemClick(ret){
    let index =ret.currentTarget.dataset.index;
    let item =ret.currentTarget.dataset.item;
 
    let chose_items = this.data.chose_items;
    chose_items.splice(index+1,chose_items.length-index+1);

    if(item.name==="请选择"){
      console.log("点击了请选择");
    }else{
  
      if(item.code == this.data.current_code){
        console.log(index);
        if(index==0){
          this.setData({
            chose_items:[]
          })
          this.getGovernmentByCode();
        }else{
          let new_item = this.data.chose_items[index-1];
          console.log(chose_items);
          //改变状态
          new_item.status="1";
          chose_items[index-1]=new_item;
          //移除目前选中
          chose_items.splice(index,1);

          this.setData({
            "chose_items":chose_items
          })
          this.getGovernmentByCode(new_item.code,new_item);
        }

      }else{
        this.getGovernmentByCode(item.code,item);
      }
     
    }
   
  },
  clickAddressItem(ret){
    let item = ret.currentTarget.dataset.index;
    // console.log(index);
    let code = item.code;
    // console.log(code);
    //==> 判断到镇
    if(code.length<12){
      this.getGovernmentByCode(code,item,this.data.currentChose);
    }else{
      //选择完成
      this.popToItem(item);
    }
    
  
  },
  /**
   * 获取省市区镇  
   */
  async getGovernmentByCode(code="",item={}){
    // console.log(code);
    this.setData({
      "searchValue":""
    })
    const response = await this.$_server("user/byCode", {
        params: {
          code: code.length > 0 ? "?code="+code:"?",
        },
    });
    let { data } = response;
    if (data.code !== 200) {
        throw data;
    }
    console.log(data);

    this.setData({
      "current_code":code,
      "ret":data
    })



    if(data.data.length>0){
      //处理数据源
      this.handleRetAction(data.data);
      this.handleAction(data.data);
      //显示选中
      let chose_items = this.data.chose_items;
       chose_items.forEach((item,index)=>{
          // console.log(index);
          item.status="";
          chose_items[index]=item;
       }); 
      let new_items = {"name":item.name,"status":"1","code":item.code};
      if(item.name){
        if(chose_items.length==0){
          chose_items.push(
            {"name":"请选择","status":"0","code":""}
          );
          chose_items.unshift(new_items);
        }else{
           let isHave = false;
          chose_items.forEach((item)=>{
            if(item.name == new_items.name){
              isHave = true;
            }
          });


          console.log(chose_items);

          if(isHave){
            chose_items[chose_items.length-1].status="1";
            chose_items.push(
              {"name":"请选择","status":"0","code":""}
            );  
          }else{
            chose_items.splice(chose_items.length-1,0,new_items);
          }
        }
  
        this.setData({
          "chose_items":chose_items
        })
    
      }
    }else{
      let chose_items = this.data.chose_items;
      if(chose_items.length==4){
        chose_items.forEach((item,index)=>{
          // console.log(index);
          item.status="";
          chose_items[index]=item;
       }); 
        let chose_item = chose_items[3];
        chose_item.name=item.name;
        chose_item.status="1";
        chose_items[3]=chose_item;
        this.setData({
          "chose_items":chose_items
        })
      }
        this.popToItem(item);
    }
 
  },
  handleRetAction(ret){
    // console.log(ret);
    let addressNameList = ret;
    addressNameList.forEach((el)=>{
      // console.log(e);
      let whole_py = pinyin.getFirstLetter(el.name);
      el["whole_py"]=whole_py;
    });
    // console.log(addressNameList);
    this.setData({
      "ret":addressNameList
    })

  },
  handleAction(ret){
 
    let addressList = ret;

    let addressNameList = [];
    for (let k in addressList) {
        addressNameList.push(addressList[k])
    }
    // console.log(addressList);
    // console.log(employeeNameList);
    let firstName = {};
    let new_alphabetList = [];

    this.data.AlphabetList.forEach((item) => {
      firstName[item] = [];
      addressNameList.forEach((el) => {
        /** 主要在这一句，el代表每个名字如 “安琪拉” ，
          pinyin.getFirstLetter(el) 取的是名字的首字母 “AQL” ，
          .substring(0, 1) 就是只取第一个字符 ‘A’ **/
        let first =  pinyin.getFirstLetter(el.name).substring(0, 1);  
        if (first == item) {
          firstName[item].push(el)
          var index = new_alphabetList.indexOf(item)
          if (index <0){
            new_alphabetList.push(item);
          }
        }
      })
    })
    // console.log(new_alphabetList);
    // 控制滚动
    wx.pageScrollTo({
      scrollTop: 0
    })

    console.log(new_alphabetList.length);
    this.setData({
      "addressNameList":firstName,
      "new_alphabetList":new_alphabetList,
      "new_alphabetList_length":new_alphabetList.length
    })

  },
  popToItem(item){
          //选中回调 
          console.log("选中");
          var pages = getCurrentPages();
          // var currPage = pages[pages.length - 1];   //当前页面
          var prevPage = pages[pages.length - 2];  //上一个页面
          wx.navigateBack({
            delta: 1,
            success:()=>{
              prevPage.onShow(item);
            }
          })
  },
  onChange(e){
    console.log(this.data.ret);
    if(e.detail !== ""){
      var temp = [];
      var val = e.detail;
      let ret = this.data.ret;
      //转化拼音
      let val_py = pinyin.getFirstLetter(val);   
      val_py = val_py.toUpperCase();
      val = val_py;

      if(!ret){return}
      ret.forEach(function(e){
  
          var name = e.name;
          var py = e.whole_py;
          if (name.indexOf(val) != -1 || py.indexOf(val) != -1) {
            temp.push(e);
          }
      });

      if (val == '') {
        temp = []
      }

      this.handleAction(temp);  

    }else{

      this.handleAction(this.data.ret);

    }
  },
  onSearch(e){
    console.log(e);
  }
 
})